package com.alibaba.day0318yk.controller;

import com.alibaba.day0318yk.pojo.Kc;
import com.alibaba.day0318yk.pojo.Kcmc;
import com.alibaba.day0318yk.pojo.User;
import com.alibaba.day0318yk.service.KcService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @description:
 * @author: Wang
 * @create: 2024-03-18 09:59
 **/
@Controller
@RequestMapping("/kc")
public class KcController {
    @Autowired
    private KcService kcService;

    /**
     * 列表页面
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    private ModelAndView list(
            @RequestParam(defaultValue = "2")Integer pageSize,
            @RequestParam(defaultValue = "1")Integer pageNum, Kc kc){
        PageHelper.startPage(pageNum,pageSize);

        List<Kc> kcList = kcService.list(kc);

        PageInfo<Kc> pageInfo = new PageInfo<>(kcList,3);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("pageInfo",pageInfo);
        modelAndView.addObject("kc",kc);
        modelAndView.setViewName("list");

        return modelAndView;
    }

    @RequestMapping("/selectName")
    @ResponseBody
    private List<Kcmc> selectName(){
        List<Kcmc> kcmcs = kcService.selectName();
        return kcmcs;
    }


    /**
     * (12)点击选课,提示选课成功,且能把当前登录人id和课程id保存到数据库（5分)
     * (13)如果当前登录人已经选择该课程再次选择则执行更新（3分)
     * (14)以上两个功能需要事务支持（3分)
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/checkKc")
    @ResponseBody
//    @Transactional
    public Integer checkKc(Integer id, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");

        Kc kc = kcService.selectkcById(id,user.getId());

        if (kc!=null){
            kcService.deleteById(id,user.getId());
            kcService.insertById(id,user.getId());
            return -1;
        }
        Integer integer = kcService.insertById(id,user.getId());
        return integer;
    }

}
